package org.yan.kangaroo.storage.service.cos;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.yan.kangaroo.common.frs.vo.request.UploadFileBase64Request;
import org.yan.kangaroo.pojo.storage.constant.FileStorageTypeEnum;
import org.yan.kangaroo.pojo.storage.entity.FileResource;
import org.yan.kangaroo.storage.service.FileResourceService;
import org.yan.kangaroo.storage.service.IFileResourceStorageService;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * @author wangx
 * @date 11/14/2019 10:29
 */
@Service("cosFileStorageService")
@Slf4j
@AllArgsConstructor
public class CosFileResourceStorageServiceImpl implements IFileResourceStorageService {
    private final CosObjectResourceClient cosObjectResourceClient;
    private final FileResourceService fileResourceService;

    @Override
    public FileResource uploadObject(UploadFileBase64Request base64Request) {
        byte[] content = Base64.getDecoder().decode(base64Request.getBase64Content());
        String key = cosObjectResourceClient.uploadFile(new ByteArrayInputStream(content), base64Request.getFileName(), base64Request.getContentType());
        FileResource fileResource = new FileResource();
        fileResource.setContentType(base64Request.getContentType());
        fileResource.setFileName(base64Request.getFileName());
        fileResource.setSize((long) content.length);
        fileResource.setStorageType(FileStorageTypeEnum.QCLOUD.getType());
        fileResource.setKeyword(key);
        return fileResourceService.insert(fileResource);
    }

    @Override
    public FileResource uploadFile(MultipartFile file) {
        String key = null;
        try {
            key = cosObjectResourceClient.uploadFile(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        FileResource fileResource = new FileResource();
        fileResource.setContentType(file.getContentType());
        fileResource.setFileName(file.getOriginalFilename());
        fileResource.setSize(file.getSize());
        fileResource.setStorageType(FileStorageTypeEnum.QCLOUD.getType());
        fileResource.setKeyword(key);
        return fileResourceService.insert(fileResource);
    }

    @Override
    public InputStream getObject(String key) {
        return cosObjectResourceClient.getFile(key);
    }
}
